package com.example.homemate.controller.house;

import com.example.homemate.model.entity.house.House;
import com.example.homemate.service.house.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/houses")
public class HouseController {

    @Autowired
    private HouseService houseService;

    @GetMapping
    public ResponseEntity<Page<House>> getHouses(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sortField,
            @RequestParam(defaultValue = "asc") String sortDirection,
            @RequestParam(required = false) String houseNumber,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long ownerId
    ) {
        Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortField);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);

        Page<House> houses = houseService.searchHouses(
                pageRequest, houseNumber, status, ownerId
        );

        return new ResponseEntity<>(houses, HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<House> getHouseById(@PathVariable Long id) {
        House house = houseService.getHouseById(id);
        return new ResponseEntity<>(house, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<House> saveHouse(@RequestBody House house) {
        House savedHouse = houseService.saveHouse(house);
        return new ResponseEntity<>(savedHouse, HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<House> updateHouse(
            @PathVariable Long id,
            @RequestBody House house
    ) {
        House updatedHouse = houseService.updateHouse(id, house);
        return new ResponseEntity<>(updatedHouse, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteHouse(@PathVariable Long id) {
        houseService.deleteHouse(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}